package com.hnjd.Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Cookie[] cookies = request.getCookies();
        String username ="";
        if(cookies!=null && cookies.length!=0){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("username")){
                    username = cookie.getValue();
                }
            }
        }
        if(!username.equals("") || request.getServletPath().indexOf("login.html")>0 || request.getServletPath().endsWith(".css")
                || request.getServletPath().endsWith(".js") || request.getServletPath().indexOf("login")>0){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            response.sendRedirect("/pages/login.html");
        }
    }
}
